<template>
<!-- 通道费发票管理 -->
<div class="home-page-container">
  <div class="channel-invoice-wrapper">
    <el-row :gutter="20">
      <!-- 油品发票金额 -->
      <el-col :span="6">
        <div class="invoice-balance">
          <div class="title">上月可开票金额(元)</div>
          <div class="balance">
            <span class="flag">¥</span>
            <span>{{invoiceBalacne}}</span>
          </div>
          <el-button size="mini" type="primary" class="invoice-btn" @click="invoiceShow=true">申请开票</el-button>
        </div>
      </el-col>
      <!-- 发票抬头信息 -->
      <el-col :span="18">
        <div class="invoice-info">
          <div class="invoice-info-top">
            <span class="title">发票及邮寄状态</span>
            <el-button size="mini" @click="gotoConfig">
              开票、收件信息更改<i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <el-row>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">开票抬头：</span>
                <span class="info">{{invoiceForm.sellerName}}</span>
              </div>
              <div class="info-item">
                <span class="label">纳税人识别号：</span>
                <span class="info">{{invoiceForm.sellerTaxNo}}</span>
              </div>
              <div class="info-item">
                <span class="label">地址和电话：</span>
                <span class="info">{{invoiceForm.sellerAddressPhone}}</span>
              </div>
              <div class="info-item">
                <span class="label">开户行和账号：</span>
                <span class="info">{{invoiceForm.sellerBankAccount}}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">收件人：</span>
                <span class="info">{{addressForm.addressee}}</span>
              </div>
              <div class="info-item">
                <span class="label">联系电话：</span>
                <span class="info">{{addressForm.addresseePhone}}</span>
              </div>
              <div class="info-item">
                <span class="label">邮寄地址：</span>
                <span class="info">{{addressForm.addresseeAddress}}</span>
              </div>
              <div class="info-item">
                <span class="label">电子邮箱：</span>
                <span class="info">{{addressForm.email}}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
  <el-card shadow="never" style="margin: 20px 0">
    <mer-search :searchConfig="formConfig" 
      :searchBar="searchBar" 
      @search="search" 
      @reset="reset(initQuery)" 
      @changeTime="(value,model)=>changeTime(value,'searchBar', 'applyStartTime', 'applyEndTime')" 
      :loading="tableLoading" :isLayout="true">
      <template slot="handler">
        <el-button size="mini" @click="download" icon="el-icon-download">导出</el-button>
      </template>
    </mer-search>
  </el-card>
  <el-card shadow="never">
    <!-- table 表格 -->
    <mer-table :loading="tableLoading" 
      :tableConfig="tableConfig" 
      :tableData="tableData" 
      :pagination="pagination" 
      @SizeChange="handleSizeChange" 
      @PageChange="pageChange">
      <template slot="applyTime" slot-scope="{row}">
          <span>{{row.createTime | formatTime }}</span>
      </template>
      <template slot="mailingTime" slot-scope="{row}">
          <span>{{row.mailingTime | formatTime }}</span>
      </template>
    </mer-table>
  </el-card>
  <apply-invoice v-if="invoiceShow" @close="invoiceShow=false;getInvoiceBlance();search()"></apply-invoice>
</div>
</template>

<script>
import listPage from '@/mixins/listPage'
import queryMix from '@/views/finance/mixins/query';
import { getChannelInvoiceBalacneApi,getQuerySendStatusApi,getQueryInvoiceStatusApi,getChannelInvoiceListApi,downloadChannelInvoiceBillApi, getAllInvoiceInfoApi, getAllInvoiceAddressApi } from '@/api/finance'
import ApplyInvoice from './components/channelInvoice/applyInvoice'
import moment from 'moment'

// 查询表单配置
let formConfig = [
  {label: '油站',type: 'select',modelName: 'gasId',placeholder: '全部',selectOptions: [],define: true,selectLabel: 'gasName',selectValue: 'gasId'},
  {label: '发票状态',type: 'select',modelName: 'invoiceStatus',placeholder: '全部',selectOptions: [],define: true,selectLabel: 'label',selectValue: 'value'},
  {label: '邮寄状态',type: 'select',modelName: 'mailingStatus',placeholder: '全部',selectOptions: [],define: true,selectLabel: 'label',selectValue: 'value'},
  {label: '申请时间',type: 'date',modelName: 'invoiceTime',model: '',dateType: 'datetimerange',format: 'yyyy-MM-dd HH:mm:ss',pickerOptions:{}, clearable:false},
]
// 表格参数配置
let tableConfig = [
  {label: '申请时间',prop: 'createTime',fixed: 'left',width: 150,slot:'applyTime'},
  {label: '开票类型',prop: 'invoiceTypeCodeName',width: 136},
  {label: '发票类型',prop: 'invoiceTypeDesc',width: 136},
  {label: '对应订单交易周期',prop: 'invoiceDateRange',width: 210},
  {label: '发票号码',prop: 'invoiceNo',width: 136},
  {label: '发票抬头',prop: 'buyerName',width: 136},
  {label: '申请开票金额(元)',prop: 'invoiceTotalPrice',width: 136},
  {label: '税额(元)',prop: 'invoiceTotalTax',width: 136},
  {label: '价税合计(元)',prop: 'invoiceTotalPriceTax',width: 136},
  {label: '发票状态',prop: 'invoiceStatusDesc',width: 136},
  {label: '邮寄状态',prop: 'mailingStatusDesc',width: 136},
  {label: '备注',prop: 'remarks',width: 136},
  {label: '邮寄日期',prop: 'mailingTime',width: 150,slot:'mailingTime'},
  {label: '快递单号',prop: 'expressNo',width: 136},
  {label: '快递名称',prop: 'expressName',width: 136},
  {label: '发票详情',prop: 'invoiceDetails',width: 150},
]
export default {
  name: 'invoice_channelInvoice',
  mixins: [listPage, queryMix],
  components:{
    ApplyInvoice
  },
  data() {
    return {
      invoiceTime: '',
      formConfig: formConfig,
      tableConfig: tableConfig,
      invoiceBalacne: 0,
      allQueryProps: {},
      invoiceShow: false,
      invoiceForm:{
        sellerName:'',
        sellerBankAccount:'',
        sellerTaxNo:'',
        sellerAddressPhone:''
      },
      addressForm:{
        addressee:'',
        addresseePhone:'',
        addresseeAddress:'',
        email:''
      },
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        // 限制时间选择范围31天
        disabledDate: (time) => {
          if (this.selectDate !== '') {
            const one = 30 * 24 * 3600 * 1000
            const minTime = this.selectDate - one
            const maxTime = this.selectDate + one
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      }
    }
  },
  created() {
    this.initPage()
    this.initInvoiceAndAddress() //解决二次刷新，数据丢失
  },
  activated(){
    this.initInvoiceAndAddress()
  },
  methods: {
    initPage() {
      this.getQueryProps()
      this.initQuery()
      this.initList(getChannelInvoiceListApi, false)
      // this.getInvoiceBlance()
      // this.ininInvoiceAndAddress()
    },
    // 设置默认查询条件，默认时间间隔当前自然月
    initQuery() {
      this.invoiceTime = ''
      this.initMonth()
      const {invoiceTime,pickerOptions} = this
      const initObj = { invoiceTime:[invoiceTime,pickerOptions] }
      this.setSearchConfig(initObj)
      // 获取查询条件：油站
      this.getAllGasStations()
    },
    // 初始化上月开票金额、发票信息and邮寄地址
    initInvoiceAndAddress(){
      this.getInvoiceBlance()
      this.getAllInvoice()
      this.getAllAddress()
    },
    // 获取查询条件：油站 发票状态 邮寄状态
    getQueryProps() {
      this.getQuerySendStatus()
      this.getQueryInvoiceStatus()
    },
    initMonth(){
      const start = moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD HH:mm:ss')
      const end = moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD HH:mm:ss')
      this.invoiceTime = [start,end]
      this.searchBar['applyStartTime'] = start
      this.searchBar['applyEndTime'] = end
    },
    //获取查询条件：邮寄状态
    async getQuerySendStatus(){
      try{
        const { code, result={} } = await getQuerySendStatusApi()
        if(code !== 200) return
        const initObj = { mailingStatus: this.optionsWrapper(result) }
        this.setSearchConfig(initObj)
      }catch(e){
        console.log(e)
      }
    },
    //获取查询条件：发票状态
    async getQueryInvoiceStatus(){
      try{
        const { code, result={} } = await getQueryInvoiceStatusApi()
        if(code !== 200) return
        const initObj = { invoiceStatus: this.optionsWrapper(result) }
        this.setSearchConfig(initObj)
      }catch(e){
        console.log(e)
      }
    },
    // 获取上月可开发票金额
    async getInvoiceBlance() {
      try {
        const lastMonthStartDate = moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD HH:mm:ss');
        const lastMonthEndDate = moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD HH:mm:ss');
        const data = {
          applyStartTime: lastMonthStartDate,
          applyEndTime: lastMonthEndDate
        }
        const { code, result = '0.00' } = await getChannelInvoiceBalacneApi(data)
        if(code !== 200) return
        this.invoiceBalacne = result
      } catch (err) {
        console.log(err)
      }
    },
      //获取发票信息
    async getAllInvoice(){
      try{
        const {code, result = []} = await getAllInvoiceInfoApi()
        if( code !==200 ) return
        this.invoiceForm = this.setDefaultInvoiceOrAddress(result)
      }catch(e){
        console.log(e)
      }
    },
    //获取邮寄地址
    async getAllAddress(){
      try{
        const {code, result = []} = await getAllInvoiceAddressApi()
        if( code !==200 ) return
        this.addressForm = this.setDefaultInvoiceOrAddress(result)
      }catch(e){
        console.log(e)
      }
    },
    //获取默认的发票或地址，若没有默认，取数组第一项
    setDefaultInvoiceOrAddress(arr = []){
      let needArr = []
      if(arr && arr.length){
        needArr = arr.filter((item)=>{
          return item.type === 0
        })
      }
      return needArr.length ? needArr[0] : {}
    },
    //发票列表导出
    download() {
      this.downloadFile(downloadChannelInvoiceBillApi, '通道费发票')
    },
    gotoConfig(){
      this.$router.push({path:'/invoice/invoiceConfig'})
    }
  }
}
</script>

<style lang="less" scoped>
.home-page-container {
  margin-top: 20px;
}
.channel-invoice-wrapper {
  margin-bottom: 20px;
  box-sizing: border-box;
  .invoice-balance {
    background: #FFF;
    height: 254px;
    padding: 35px 30px;
    display: flex;
    flex-direction: column;
    .title {
      font-size: 14px;
      color: #A6A6A6;
      margin-bottom: 17px;
    }
    .balance {
      font-size: 20px;
      color: #222222;
      margin-bottom: 75px;
      .flag {
        padding-right: 5px;
        font-size: 10px;
      }
    }
    .invoice-btn {
      width: 100px;
    }
  }

  .invoice-info {
    background: #FFF;
    height: 254px;
    padding: 35px 30px;
    font-size: 12px;
    .invoice-info-top{
      margin-bottom: 35px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        border-left: 3px solid #4B7EFE;
        padding-left: 5px;
        font-weight: bold;
        font-size: 16px;
      }
    }
    .info-item {
      margin-bottom: 16px;
      display: flex;
      .label {
        color: #A6A6A6;
        white-space: nowrap;
      }
      .info {
        color: #222222;
        word-break: break-all;
      }
    }
  }
}
</style>
